﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebApi.Core.AuthHelper;
using WebApi.Core.Common.Helper;
using WebApi.Core.IService;
using WebApi.Core.Model;
using WebApi.Core.Model.Entity;
using WebApi.Core.Service;

namespace WebApi.Core.Controllers
{
    /// <summary>
    /// 用户管理
    /// </summary>
    //[Route("api/[controller]/[action]")]
    //[ApiController]
    public class UserController : BaseController
    {
        public readonly PermissionRequirement _requirement;
        private readonly IUserService _userService;
        public UserController(IUserService userService, PermissionRequirement requirement)
        {
            _userService = userService;
            _requirement = requirement;
        }

        #region MyRegion
        /// <summary>
        /// hello请求
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public IActionResult Hello()
        {
            return Ok("Hello World");
        }

        /// <summary>
        /// 获取User实体
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        [ApiExplorerSettings(IgnoreApi = true)]
        public IActionResult User(User user)
        {
            return Ok(user);
        }
        #endregion

        #region JWT
        [HttpPost]
        public IActionResult Login(string role)
        {
            string jwtStr = string.Empty;
            bool suc = false;

            if (!string.IsNullOrEmpty(role))
            {
                //将用户id和角色名，作为单独的自定义变量封装进 token 字符串中。
                TokenModel tokenModel = new TokenModel { Uid = "admin", Role = role };
                jwtStr = JwtHelper.IssueJwt(tokenModel);   //登录，获取到一定规则的 Token 令牌
                suc = true;
            }
            else
            {
                jwtStr = "login fail!!!";
            }

            return Ok(new
            {
                success = suc,
                token = jwtStr
            });
        }

        [HttpPost]
        public IActionResult Login2(string role)
        {
            string jwtStr = string.Empty;
            bool suc = false;

            if (!string.IsNullOrEmpty(role))
            {
                //将用户id和角色名，作为单独的自定义变量封装进 token 字符串中。
                TokenModel tokenModel = new TokenModel { Uid = "admin", Role = role };
                jwtStr = JwtHelper.IssueJwt(tokenModel);   //登录，获取到一定规则的 Token 令牌
                suc = true;
            }
            else
            {
                jwtStr = "login fail!!!";
            }

            return Ok(new
            {
                success = suc,
                token = jwtStr
            });
        }

        /// <summary>
        /// 需要Admin权限
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Roles = "Admin")]
        public IActionResult Admin()
        {
            return Ok("hello admin");
        }


        /// <summary>
        /// 需要System权限
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Roles = "System")]
        public IActionResult System()
        {
            return Ok("hello System");
        }

        /// <summary>
        /// 需要System 和 Admin权限
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        //[Authorize(Roles = "SystemOrAdmin")]
        //使用策略进行鉴权
        [Authorize(Policy = "SystemOrAdmin")]
        public IActionResult SystemAndAdmin()
        {
            return Ok("hello SystemOrAdmin");
        }

        #region 测试自定义
        /// <summary>
        /// RolePolicy1
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Policy = "Permission")]
        public IActionResult RolePolicy1()
        {
            return Ok("hello RolePolicy1");
        }
        /// <summary>
        /// RolePolicy2
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Policy = "Permission")]
        public IActionResult RolePolicy2()
        {
            return Ok("hello RolePolicy2");
        }
        /// <summary>
        /// RolePolicy3
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Policy = "Permission")]
        public IActionResult RolePolicy3()
        {
            return Ok("hello RolePolicy3");
        }
        #endregion


        /// <summary>
        /// 解析Token
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public IActionResult ParseToken()
        {
            //需要截取Bearer 
            var tokenHeader = HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
            var user = JwtHelper.SerializeJwt(tokenHeader);
            return Ok(user);
        }

        #endregion


        /////////////////////////////////////////////////////////////


        /// <summary>
        /// 根据id获取数据
        /// </summary>
        /// <param name="id">参数id</param>
        /// <returns></returns>
        //[HttpGet("{id}", Name = "Get")]
        [HttpGet]
        public async Task<IActionResult> GetUser(int id)
        {
            #region new方式
            //IUserService userService = new UserService();
            //UserEntity user = await userService.QueryByID(id);
            #endregion

            #region DI
            UserEntity user = await _userService.QueryByID(id);
            #endregion

            return Ok(user);
        }


        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="id">参数id</param>
        /// <returns></returns>
        //[HttpGet("{id}", Name = "Get")]
        [HttpPost]
        public async Task<IActionResult> Add(UserEntity user)
        {
            #region MyRegion
            //IUserService userService = new UserService();
            //var count = await userService.Add(user);
            #endregion

            var count = await _userService.Add(user);
            return Ok(count);
        }

        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="id">参数id</param>
        /// <returns></returns>
        //[HttpGet("{id}", Name = "Get")]
        [HttpPost]
        public async Task<IActionResult> Update(UserEntity user)
        {
            #region MyRegion
            //IUserService userService = new UserService();
            //var sucess = await userService.Update(user);
            #endregion

            var sucess = await _userService.Update(user);
            return Ok(sucess);
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="id">参数id</param>
        /// <returns></returns>
        //[HttpGet("{id}", Name = "Get")]
        [HttpPost]
        public async Task<IActionResult> Delete(object[] ids)
        {
            #region MyRegion
            //IUserService userService = new UserService();
            //var sucess = await userService.DeleteByIds(ids);
            #endregion

            var sucess = await _userService.DeleteByIds(ids);
            return Ok(sucess);
        }


        /// <summary>
        /// 测试autofac
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AutofacTest()
        {
            var count = await _userService.GetCount();
            return Ok(count);
        }



    }
}